<ng-container
  *ngIf="{
    user: user$ | async,
    templates: templates$ | async,
    activeTemplate: activeTemplate$ | async,
    activeTemplatesTab: activeTemplatesTab$ | async,
    activeTemplateListItem: activeTemplateListItem$ | async,
    generatingTemplate: generatingTemplate$ | async,
    generatingEndpoint: generatingEndpoint$ | async,
    lastGeneratedEndpoint: lastGeneratedEndpoint$ | async,
    demoEndpoint: demoEndpoint$ | async
  } as data"
>
  <ng-container
    *ngIf="{
      isFree: !data.user || data.user.plan === 'FREE',
      isPaid: data.user && data.user.plan !== 'FREE',
      canGenerateTemplate:
        promptTemplate.value &&
        (data.generatingTemplate === 'NONE' ||
          data.generatingTemplate === 'DONE') &&
        data.user?.templatesQuotaUsed < data.user?.templatesQuota,
      canGenerateEndpoint:
        promptEndpoint.value &&
        (data.generatingEndpoint === 'NONE' ||
          data.generatingEndpoint === 'DONE') &&
        data.user?.templatesQuotaUsed < data.user?.templatesQuota
    } as flags"
  >
    <div class="modal-header border-0 pb-0">
      <ul class="nav nav-tabs">
        <li class="nav-item">
          <a
            class="nav-link"
            [ngClass]="{ active: data.activeTemplatesTab === 'LIST' }"
            (click)="setActiveTab('LIST')"
          >
            JSON Templates
          </a>
        </li>
        <li class="nav-item">
          <a
            class="nav-link"
            [ngClass]="{
              active: data.activeTemplatesTab === 'GENERATE_TEMPLATE'
            }"
            (click)="setActiveTab('GENERATE_TEMPLATE')"
          >
            <app-svg icon="magic" class="me-2 text-warning"></app-svg>
            <!-- Display specific title for demo -->
            {{ flags.isFree ? 'AI assistants' : 'Generate JSON templates' }}
          </a>
        </li>
        <li *ngIf="flags.isPaid" class="nav-item">
          <a
            class="nav-link"
            [ngClass]="{
              active: data.activeTemplatesTab === 'GENERATE_ENDPOINT'
            }"
            (click)="setActiveTab('GENERATE_ENDPOINT')"
          >
            <app-svg icon="magic" class="me-2 text-warning"></app-svg>
            Generate HTTP endpoints
          </a>
        </li>
      </ul>
    </div>
    <div class="modal-body">
      <!-- List tab -->
      <div
        *ngIf="data.activeTemplatesTab === 'LIST'"
        class="h-100"
        [ngClass]="{ 'd-flex': data.templates }"
      >
        <ng-container *ngIf="data.templates; else noTemplates">
          <div class="col-4 me-2 h-100 d-flex flex-column">
            <div class="mb-2">
              <app-filter
                filterName="templates"
                [focusableInput]="focusableInputs.TEMPLATES_FILTER"
              ></app-filter>
            </div>
            <div class="list-group list-group-flush h-100 overflow-auto">
              <button
                *ngFor="let template of data.templates"
                class="list-group-item list-group-item-action"
                [ngClass]="{
                  active: template.id === data.activeTemplateListItem?.id
                }"
                type="button"
                (click)="setActiveTemplateListItem(template)"
              >
                <div class="text-truncate">
                  {{ template.name }}
                </div>
              </button>
            </div>
          </div>

          <div class="col ps-4 d-flex flex-column h-100">
            <app-editor
              [readOnly]="true"
              [text]="data.activeTemplate?.content"
              [options]="defaultEditorOptions.options"
              [mode]="data.activeTemplate?.type"
              uuid="templatePreview"
            ></app-editor>
            <p
              *ngIf="data.activeTemplate?.source"
              class="px-2 pt-2 mb-0 text-muted"
            >
              Source:
              <a href="{{ data.activeTemplate?.source }}" target="_blank">{{
                data.activeTemplate?.source
              }}</a>
            </p>
          </div>
        </ng-container>
      </div>

      <!-- Generate tab when user is connected and paid -->
      @if (data.activeTemplatesTab === 'GENERATE_TEMPLATE' && flags.isPaid) {
        <div class="d-flex flex-column h-100">
          <div class="input-group mb-2">
            <input
              type="text"
              class="form-control"
              [maxlength]="maxPromptLength"
              [formControl]="promptTemplate"
              placeholder='Prompt, e.g. "invoices", "customers", "bird species" etc.'
              (keydown.enter)="flags.canGenerateTemplate && generateTemplate()"
            />
            <ng-container
              [ngTemplateOutlet]="templatingCheckbox"
            ></ng-container>
            <button
              id="templates-generate-button"
              type="button"
              class="btn btn-secondary"
              (click)="generateTemplate()"
              [disabled]="!flags.canGenerateTemplate"
            >
              Generate
            </button>
            <div
              *ngIf="data.generatingTemplate === 'INPROGRESS'"
              class="input-group-text"
            >
              <app-spinner></app-spinner>
            </div>
          </div>
          <app-editor
            [formControl]="generatedTemplateBody"
            [options]="defaultEditorOptions.options"
            [mode]="defaultEditorOptions.mode"
            uuid="templateGenPreview"
          ></app-editor>
          <p class="px-2 pt-2 mb-0 text-muted fst-italic">
            Note: Depending on its length, template generation may take time.
            You can safely close this modal and return later to view the result.
          </p>
        </div>
      }

      <!-- Generate endpoint tab when user is connected and paid -->
      @if (data.activeTemplatesTab === 'GENERATE_ENDPOINT' && flags.isPaid) {
        <div class="d-flex flex-column h-100">
          <div class="input-group mb-2">
            <input
              type="text"
              class="form-control"
              [maxlength]="maxPromptLength"
              [formControl]="promptEndpoint"
              placeholder='Prompt, e.g. "add a new invoice", "delete a contact", "get all movies", etc.'
              (keydown.enter)="flags.canGenerateEndpoint && generateEndpoint()"
            />
            <ng-container
              [ngTemplateOutlet]="templatingCheckbox"
            ></ng-container>
            <button
              id="templates-endpoint-generate-button"
              type="button"
              class="btn btn-secondary"
              (click)="generateEndpoint()"
              [disabled]="!flags.canGenerateEndpoint"
            >
              Generate
            </button>
            <div
              *ngIf="data.generatingEndpoint === 'INPROGRESS'"
              class="input-group-text"
            >
              <app-spinner></app-spinner>
            </div>
          </div>

          <fieldset class="flex-fill d-flex flex-column">
            <legend>Endpoint preview</legend>

            <div [ngClass]="{ 'opacity-25': !data.lastGeneratedEndpoint }">
              <div class="d-flex align-items-center mb-2">
                <span
                  class="color-method-{{
                    !data.lastGeneratedEndpoint?.method
                      ? 'all'
                      : data.lastGeneratedEndpoint?.method
                  }} me-2"
                  >{{
                    !data.lastGeneratedEndpoint?.method
                      ? 'method'
                      : (data.lastGeneratedEndpoint?.method | uppercase)
                  }}
                </span>
                <span
                  >/{{
                    !data.lastGeneratedEndpoint?.endpoint
                      ? 'path'
                      : data.lastGeneratedEndpoint?.endpoint
                  }}</span
                >
              </div>
              <div class="mb-2">
                <span class="fst-italic">Description:</span>
                {{ data.lastGeneratedEndpoint?.documentation }}
              </div>
              <div class="mb-2 fst-italic">Response body:</div>
            </div>

            <app-editor
              [ngClass]="{ 'opacity-25': !data.lastGeneratedEndpoint }"
              [options]="defaultEditorOptions.options"
              [mode]="defaultEditorOptions.mode"
              uuid="endpointGenPreview"
              [value]="data.lastGeneratedEndpoint?.responses[0]?.body"
            ></app-editor>
          </fieldset>
          <p class="px-2 pt-2 mb-0 text-muted fst-italic">
            Note: Depending on its length, endpoint generation may take time.
            You can safely close this modal and return later to view the result.
          </p>
        </div>
      }

      <!-- Demo generate tab when no user or FREE plan -->
      <div
        *ngIf="data.activeTemplatesTab === 'GENERATE_TEMPLATE' && flags.isFree"
        class="d-flex h-100 no-interact justify-content-center"
      >
        <div @fade class="d-flex flex-column h-100">
          <div class="d-flex flex-column h-100 p-4 rounded bg-dark">
            <div class="d-flex align-items-center mb-4">
              <div class="input-group shadow border-radius">
                <input
                  type="text"
                  class="form-control"
                  [formControl]="demoPrompt"
                  tabindex="-1"
                />
                <button
                  id="demoGenerateButton"
                  type="button"
                  class="btn btn-secondary"
                  tabindex="-1"
                >
                  Generate
                </button>
              </div>
              <div *ngIf="isDemoLoading$ | async" class="input-group-text">
                <app-spinner></app-spinner>
              </div>
            </div>

            <fieldset class="flex-fill d-flex flex-column">
              <legend>Endpoint preview</legend>

              <div [ngClass]="{ 'opacity-25': !data.demoEndpoint }">
                <div class="d-flex align-items-center mb-2">
                  <span
                    class="color-method-{{
                      !data.demoEndpoint?.method
                        ? 'all'
                        : data.demoEndpoint?.method
                    }} me-2"
                    >{{
                      !data.demoEndpoint?.method
                        ? 'method'
                        : (data.demoEndpoint?.method | uppercase)
                    }}
                  </span>
                  <span
                    >/{{
                      !data.demoEndpoint?.endpoint
                        ? 'path'
                        : data.demoEndpoint?.endpoint
                    }}</span
                  >
                </div>
                <div class="mb-2">
                  <span class="fst-italic">Description:</span>
                  {{ data.demoEndpoint?.documentation }}
                </div>
                <div class="mb-2 fst-italic">Response body:</div>
              </div>

              <app-editor
                [ngClass]="{ 'opacity-25': !data.demoEndpoint }"
                class="shadow"
                [readOnly]="true"
                [hideCursor]="true"
                tabindex="-1"
                [value]="data.demoEndpoint?.body"
                [options]="defaultEditorOptions.options"
                [mode]="defaultEditorOptions.mode"
                uuid="demoTemplateGenPreview"
              ></app-editor>
            </fieldset>
          </div>
          <div class="mt-auto">
            <h4 class="text-center my-4 text-shadow w-75 mx-auto">
              Generate your own templates and endpoints using our AI assistants
              and prototype faster than ever
            </h4>
          </div>
        </div>
      </div>
    </div>

    <div class="modal-footer justify-content-space-between">
      <div
        *ngIf="
          flags.isPaid &&
          (data.activeTemplatesTab === 'GENERATE_TEMPLATE' ||
            data.activeTemplatesTab === 'GENERATE_ENDPOINT')
        "
        class="col-6 d-flex align-items-center"
      >
        <p
          class="mb-0"
          [ngClass]="{
            'text-warning':
              data.user?.templatesQuotaUsed >= data.user?.templatesQuota
          }"
        >
          Quota used ({{ data.user?.templatesQuotaUsed }}/{{
            data.user?.templatesQuota
          }})
        </p>
        <a
          class="btn btn-link btn-icon text-primary ps-2"
          href="{{ accountUrl }}"
          target="_blank"
        >
          My account
          <app-svg icon="open_in_new" class="ps-1" size="12"></app-svg>
        </a>
      </div>

      <div class="ms-auto">
        <button
          type="button"
          class="btn btn-secondary modal-close"
          (click)="close()"
        >
          Close
        </button>

        <!-- Display creation CTA only for templates or if paid user on generate tab -->
        <ng-container
          *ngIf="
            data.activeTemplatesTab === 'LIST' ||
            (data.activeTemplatesTab === 'GENERATE_TEMPLATE' && flags.isPaid)
          "
        >
          <button
            *ngIf="data.templates"
            type="button"
            class="btn btn-primary ms-2"
            (click)="
              createCRUDRoute(data.activeTemplatesTab, data.activeTemplate)
            "
            ngbTooltip="Automatically creates a CRUD route and a data bucket from the template"
          >
            <app-svg icon="endpoints" class="me-1"></app-svg>Create CRUD
          </button>
          <button
            *ngIf="data.templates"
            type="button"
            class="btn btn-primary ms-2"
            (click)="
              createGetRoute(data.activeTemplatesTab, data.activeTemplate)
            "
            ngbTooltip="Automatically creates an HTTP GET route with the chosen template as the response body"
          >
            <app-svg icon="endpoint" class="me-1"></app-svg>Create GET route
          </button>
        </ng-container>
        <!-- Display creation CTA for endpoint generation -->
        <ng-container
          *ngIf="
            data.activeTemplatesTab === 'GENERATE_ENDPOINT' && flags.isPaid
          "
        >
          <button
            type="button"
            class="btn btn-primary ms-2"
            (click)="createEndpoint()"
            ngbTooltip="Automatically creates an HTTP route with the generated data"
            [disabled]="!data.lastGeneratedEndpoint"
          >
            <app-svg icon="endpoint" class="me-1"></app-svg>Create HTTP route
          </button>
        </ng-container>
        <a
          *ngIf="
            flags.isFree &&
            (data.activeTemplatesTab === 'GENERATE_TEMPLATE' ||
              data.activeTemplatesTab === 'GENERATE_ENDPOINT')
          "
          class="btn btn-warning ms-2"
          href="{{ cloudPlansURL }}"
          target="_blank"
        >
          Discover our Cloud plans
        </a>
      </div>
    </div>
  </ng-container>
</ng-container>

<ng-template #noTemplates>
  <p class="message">Templates could not be loaded</p>
</ng-template>

<ng-template #templatingCheckbox>
  <app-toggle
    id="templates-generate-option"
    class="mx-2"
    [uncheckable]="true"
    [formControl]="templatingToggle"
    prefix="templatingToggle"
    [items]="[
      {
        icon: 'data',
        tooltip: 'Use templating helpers (e.g. {{ faker person.firstname}} )'
      }
    ]"
  ></app-toggle>
</ng-template>
